package ru.hh.team02.chat.utils;

import ru.hh.team02.chat.server.Services;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class StringSocket {
    private final Socket socket;
    
    private ObjectInputStream in;
    private ObjectOutputStream out;

    /**
     * Whapper for a socket which opens streams and handles their closing along with the socket.
     * @param socket Socket to wrap.
     */
    public StringSocket(Socket socket) throws IOException {
        this.socket = socket;
        out = new ObjectOutputStream(socket.getOutputStream());
        out.flush();
        in = new ObjectInputStream(socket.getInputStream());
    }

    /**
     * Read from socket
     * @return read string
     * @throws IOException
     */
    public String read() throws IOException  {
        try {
            return (String)in.readObject();
        } catch (ClassNotFoundException e) {
            Services.ADMIN_LOGGER.write("this should never happen");
        }
        return "";
    }

    /**
     * Write to socket
     * @return string to write
     * @throws IOException
     */
    public void write(String message) throws IOException {
        out.writeObject(message);
        out.flush();
    }

    /**
     * Close in and out streams and the socket.
     */
    public void close() {
        try {
            out.close();
        } catch (IOException ioException1) {
            Services.ADMIN_LOGGER.write("can't close output stream because of" + ioException1.getMessage());
        } finally {
            try {
                in.close();
            } catch(IOException ioException2) {
                Services.ADMIN_LOGGER.write("can't close input stream because of " + ioException2.getMessage());
            } finally {
                try {
                    socket.close();
                } catch (IOException ioException3) {
                    Services.ADMIN_LOGGER.write("can't close socket because of " + ioException3.getMessage());
                }
            }
        }
    }
    
}